//
//  MethodTool.m
//  BeiChenLive
//
//  Created by 洪钻 on 2021/4/20.
//

#import "MethodTool.h"
#import <AVKit/AVKit.h>
#import <AVFoundation/AVFoundation.h>
// 公钥：
const NSString *AESKey = @"psj8AKg2nsm5osWyJTtV4Yxv1rJV0fT9Vr7EGB8zZL54vlHdTTgfW576VJfCcK5w";
NSString *const kInitVector = @"BKQno1y92GOH77VOmRAfySzX0YHGTgwJ3fBsXc3g9QTUoswohXhvNYkLCsGcIKsm";

#define ScreenWidth  ([UIScreen mainScreen].bounds.size.width)
#define ScreenHeight ([UIScreen mainScreen].bounds.size.height)

@implementation MethodTool

+ (UIViewController*)getcurrentViewController{

    UIViewController* vc = [UIApplication sharedApplication].keyWindow.rootViewController;
    while (1) {
        if ([vc isKindOfClass:[UITabBarController class]]) {
            vc = ((UITabBarController*)vc).selectedViewController;
    }
        if ([vc isKindOfClass:[UINavigationController class]]) {
            vc = ((UINavigationController*)vc).visibleViewController;
        }
        if (vc.presentedViewController) {
            vc = vc.presentedViewController;
        }else{
            break;
       }
    }
    return vc;
}

+(UIImage *)capturImageWithUIView:(UIView *)view{

    //开启位图上下文
    UIGraphicsBeginImageContext(view.bounds.size);
    //获取当前位图
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    //将视图渲染到位图上
    [view.layer renderInContext:ctx];
    //获取当前图片
    UIImage *currentImage = UIGraphicsGetImageFromCurrentImageContext();
    //结束位图编辑
    UIGraphicsEndImageContext();
    return currentImage;

}

+(UIImage*)convertViewToImage:(UIView*)view{
    
    CGSize s = view.bounds.size;
    // 下面方法，第一个参数表示区域大小。第二个参数表示是否是非透明的。如果需要显示半透明效果，需要传NO，否则传YES。第三个参数就是屏幕密度了
    UIGraphicsBeginImageContextWithOptions(s, NO, [UIScreen mainScreen].scale);
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;

}

+ (NSData *)compressOriginalImage:(UIImage *)image toMaxDataSizeKBytes:(CGFloat)size
{
    UIImage *OriginalImage = image;
    
    // 执行这句代码之后会有一个范围 例如500m 会是 100m～500k
    NSData * data = UIImageJPEGRepresentation(image, 1.0);
    CGFloat dataKBytes = data.length/1000.0;
    CGFloat maxQuality = 0.9f;
    
    // 执行while循环 如果第一次压缩不会小雨100k 那么减小尺寸在重新开始压缩
    while (dataKBytes > size)
    {
        while (dataKBytes > size && maxQuality > 0.1f)
        {
            maxQuality = maxQuality - 0.1f;
            data = UIImageJPEGRepresentation(image, maxQuality);
            dataKBytes = data.length / 1000.0;
            if(dataKBytes <= size )
            {
                return data;
            }
        }
        OriginalImage =[self compressOriginalImage:OriginalImage toWidth:OriginalImage.size.width * 0.8];
        image = OriginalImage;
        data = UIImageJPEGRepresentation(image, 1.0);
        dataKBytes = data.length / 1000.0;
        maxQuality = 0.9f;
    }
    return data;
}

#pragma mark - 改变图片的大小
+(UIImage *)compressOriginalImage:(UIImage *)image toWidth:(CGFloat)targetWidth
{
    CGSize imageSize = image.size;
    CGFloat Originalwidth = imageSize.width;
    CGFloat Originalheight = imageSize.height;
    CGFloat targetHeight = Originalheight / Originalwidth * targetWidth;
    UIGraphicsBeginImageContext(CGSizeMake(targetWidth, targetHeight));
    [image drawInRect:CGRectMake(0,0,targetWidth,  targetHeight)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

+ (UIImage*)createQRWithString:(NSString*)text QRSize:(CGSize)size;
{
    
    NSData *stringData = [text dataUsingEncoding: NSUTF8StringEncoding];
    
//生成
    CIFilter *qrFilter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
    [qrFilter setValue:stringData forKey:@"inputMessage"];
    [qrFilter setValue:@"H" forKey:@"inputCorrectionLevel"];
    
     
//上色
    CIFilter *colorFilter = [CIFilter filterWithName:@"CIFalseColor"
                                       keysAndValues:
                             @"inputImage",qrFilter.outputImage,
                             @"inputColor0",[CIColor colorWithCGColor:[UIColor blackColor].CGColor],
                             @"inputColor1",[CIColor colorWithCGColor:[UIColor whiteColor].CGColor],
                             nil];
    
    CIImage *qrImage = colorFilter.outputImage;
    
    
//绘制
    CGImageRef cgImage = [[CIContext contextWithOptions:nil] createCGImage:qrImage fromRect:qrImage.extent];
    UIGraphicsBeginImageContext(size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetInterpolationQuality(context, kCGInterpolationNone);
    CGContextScaleCTM(context, 1.0, -1.0);
    CGContextDrawImage(context, CGContextGetClipBoundingBox(context), cgImage);
    UIImage *codeImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    CGImageRelease(cgImage);
    
    return codeImage;
}

+(UIImage *)getScrollViewImage:(UIScrollView *)scrollView
{
//        UIImage* image = nil;
//    //如果是ScrollView的话用:
//    //UIScrollView *WY_scrollView = self.scrollView;
//
//        UIGraphicsBeginImageContextWithOptions(scrollView.contentSize, scrollView.opaque, 0.0);
//        CGPoint saveContentOffset = scrollView.contentOffset;
//        CGRect saveFrame = scrollView.frame;
//
//        scrollView.contentOffset = CGPointZero;
//        scrollView.frame = CGRectMake(0, 0, scrollView.contentSize.width, scrollView.contentSize.height);
//
//       [scrollView.layer renderInContext: UIGraphicsGetCurrentContext()];
//       image = UIGraphicsGetImageFromCurrentImageContext();
//
//            scrollView.contentOffset = saveContentOffset;
//            scrollView.frame = saveFrame;
//        UIGraphicsEndImageContext();
//
//        return image;
    
    UIImage *image = nil;
    
    UIGraphicsBeginImageContextWithOptions(scrollView.contentSize,scrollView.opaque,0);
    CGPoint saveContentOffSet = scrollView.contentOffset;
    CGRect saveFrame = scrollView.frame;
    scrollView.contentOffset = CGPointZero;
    scrollView.frame = CGRectMake(0, 0, scrollView.contentSize.width, scrollView.contentSize.height);
    [scrollView.layer renderInContext:UIGraphicsGetCurrentContext()];
    image = UIGraphicsGetImageFromCurrentImageContext();
    scrollView.contentOffset = saveContentOffSet;
    scrollView.frame = saveFrame;
    UIGraphicsEndImageContext();
    
    return image;
    
}

//汉字转拼音之后，截取首字母，并大写
+(NSString *)transformCharacter:(NSString*)sourceStr
{
    //先将原字符串转换为可变字符串
    NSMutableString *ms = [NSMutableString stringWithString:sourceStr];
    
    if (ms.length) {
        //将汉字转换为拼音
        CFStringTransform((__bridge CFMutableStringRef)ms, 0, kCFStringTransformToLatin, NO);
        //将拼音的声调去掉
        CFStringTransform((__bridge CFMutableStringRef)ms, 0,kCFStringTransformStripDiacritics,NO);
        //将字符串所有字母大写
        NSString *upStr = [ms uppercaseString];
        //截取首字母
        NSString *firstStr = [upStr substringToIndex:1];
        return firstStr;
    }
    return @"#";
}

+(UIImage *)getVideoFirstImageWithURL:(NSURL *)url{
    AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:url options:nil];
     
     AVAssetImageGenerator *gen = [[AVAssetImageGenerator alloc] initWithAsset:asset];
     
    gen.appliesPreferredTrackTransform = YES;
     
     CMTime time = CMTimeMakeWithSeconds(0.0, 600);
     
     NSError *error = nil;
     
     CMTime actualTime;
     
     CGImageRef image = [gen copyCGImageAtTime:time actualTime:&actualTime error:&error];
     
     UIImage *thumb = [[UIImage alloc] initWithCGImage:image];
     
     CGImageRelease(image);
     
     return thumb;
        
}

+ (void)getThumbnailImage:(NSURL *)videoURL completion:(MyImageBlock)handler {

    
    
    
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{

        AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:videoURL options:nil];
        
        NSParameterAssert(asset);//断言
        
        AVAssetImageGenerator *generator = [[AVAssetImageGenerator alloc] initWithAsset:asset];
        
        generator.appliesPreferredTrackTransform = YES;
        
        CMTime time = CMTimeMakeWithSeconds(0.0, 60);
        
        NSError *error = nil;
        
        CMTime actualTime;
        
        CGImageRef imageRef = [generator copyCGImageAtTime:time actualTime:&actualTime error:&error];
        
        UIImage *thumb = [[UIImage alloc] initWithCGImage:imageRef];
        
        CGImageRelease(imageRef);
        
        dispatch_async(dispatch_get_main_queue(), ^{
            handler(thumb);
        });
    });
}

+(void)playVideoWithURL:(NSString *)videoUrl{
    //创建播放单元
    AVPlayerItem* item = [AVPlayerItem playerItemWithURL:[NSURL URLWithString:videoUrl]];
    //创建播放器
    AVPlayer* player = [AVPlayer playerWithPlayerItem:item];        //使用播放单元生成相应的播放器
    //切换播放内容时
    [player replaceCurrentItemWithPlayerItem:item];
    //创建播放层，将playerLayer添加到view上即可播放
//    AVPlayerLayer* playerLayer = [AVPlayerLayer playerLayerWithPlayer:self.myPlayer];
    
    
    
    AVPlayerViewController* playerVC = [[AVPlayerViewController alloc] init];
    //设置播放器
    playerVC.player = player;
    //设置播放范围
    playerVC.view.frame = CGRectMake(0, 0, ScreenWidth, ScreenHeight);

    /** 设置所播放视频的适配显示范围
     *  AVLayerVideoGravityResizeAspectFill :  显示尺寸适配，保证适配内容不变形的情况下铺满显示区域，画面可能会有截断
     *  AVLayerVideoGravityResizeAspect : 保证视频不变形，画面全部显示，可能不能铺满显示区域
     *  AVLayerVideoGravityResize : 保证视频铺满显示区域，画面全部显示，但视频内容可能会有变形
     */
    playerVC.videoGravity = AVLayerVideoGravityResizeAspectFill;
    //显示播放开始，播放进度条等控件
    playerVC.showsPlaybackControls = YES;

    
    
    [[self getcurrentViewController] presentViewController:playerVC animated:YES completion:nil];
}

+ (NSInteger)getVideoTimeByUrlString:(NSString *)urlString {
    NSURL *videoUrl = [NSURL URLWithString:urlString];
    AVURLAsset *avUrl = [AVURLAsset assetWithURL:videoUrl];
    CMTime time = [avUrl duration];
    int seconds = ceil(time.value/time.timescale);
    return seconds;
}

+ (NSDictionary *)getVideoInfoWithSourcePath:(NSString *)path{
    AVURLAsset * asset = [AVURLAsset assetWithURL:[NSURL fileURLWithPath:path]];
    CMTime   time = [asset duration];
    int seconds = ceil(time.value/time.timescale);

    unsigned long long fileSize = [[NSFileManager defaultManager] attributesOfItemAtPath:path error:nil].fileSize;

    return @{@"size" : @(fileSize),
             @"duration" : @(seconds)};
}

+(void)alertTitle:(NSString *)title{
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:nil preferredStyle:(UIAlertControllerStyleAlert)];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:nil];
    UIAlertAction *sure = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alert addAction:cancel];
    [alert addAction:sure];
    [[self getcurrentViewController] presentViewController:alert animated:YES completion:nil];
}

+(void)alertTitle:(NSString *)title complete:(void (^)(UIAlertAction * _Nonnull action))complete{
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:nil preferredStyle:(UIAlertControllerStyleAlert)];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:nil];
    UIAlertAction *sure = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        complete(action);
    }];
    [alert addAction:cancel];
    [alert addAction:sure];
    [[self getcurrentViewController] presentViewController:alert animated:YES completion:nil];
}

+(void)alertTitle:(NSString *)title array:(NSArray *)array complete:(void (^)(NSInteger index ))complete{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:nil preferredStyle:(UIAlertControllerStyleActionSheet)];
    
    for (int i = 0;i < array.count;i++) {
        NSString *btnTitle = array[i];
        UIAlertAction *action = [UIAlertAction actionWithTitle:btnTitle style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
            complete(i);
        }];
        [alert addAction:action];
    }
    
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:nil];
    
    [alert addAction:cancel];
    
    [[self getcurrentViewController] presentViewController:alert animated:YES completion:nil];
}

+(BOOL)isEmpty:(id)object{
    if (object == nil) {
        return YES;
    }else if ([object isEqual:NULL]){
        return YES;
    }else if (object == [NSNull null]){
        return YES;
    }
    else{
        return NO;
    }
}




+(void)interceptTextField:(UITextField *)textField textLength:(NSInteger)textLength{
    NSString *language = [[[UITextInputMode activeInputModes] firstObject] primaryLanguage];
    NSInteger max = textLength;
    NSString *name = textField.text;
    if ([language isEqualToString:@"zh-Hans"]) {
        UITextRange *range = [textField markedTextRange];
        UITextPosition *start = range.start;
        UITextPosition *end = range.end;
        NSInteger selLength = [textField offsetFromPosition:start toPosition:end];
        NSInteger contentLength = textField.text.length - selLength;
        if (contentLength > max) {
            textField.text = [textField.text substringToIndex:max];
        }
    }else {
        if (name.length > max) {
            textField.text = [textField.text substringToIndex:max];
        }
    }
}

/**
 textView 截取
 */
+(void)interceptTextView:(UITextView *)textView textLength:(NSInteger)textLength{
    NSString *language = [[[UITextInputMode activeInputModes] firstObject] primaryLanguage];
    NSInteger max = textLength;
    NSString *name = textView.text;
    if ([language isEqualToString:@"zh-Hans"]) {
        UITextRange *range = [textView markedTextRange];
        UITextPosition *start = range.start;
        UITextPosition *end = range.end;
        NSInteger selLength = [textView offsetFromPosition:start toPosition:end];
        NSInteger contentLength = textView.text.length - selLength;
        if (contentLength > max) {
            textView.text = [textView.text substringToIndex:max];
        }
    }else {
        if (name.length > max) {
            textView.text = [textView.text substringToIndex:max];
        }
    }
}


@end
